package com.duanzz.config;

import com.duanzz.pojo.Configuration;
import com.duanzz.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream in) throws DocumentException {
        //调用dom4j进行解析
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(in);
        Element rootElement = document.getRootElement();
        //获取命名空间
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectElementList = rootElement.selectNodes("//select");
        List<Element> insertElementList = rootElement.selectNodes("//insert");
        List<Element> updateElementList = rootElement.selectNodes("//update");
        List<Element> deleteElementList = rootElement.selectNodes("//delete");

        List<Element> elementList = new ArrayList<>();
        elementList.addAll(selectElementList);
        elementList.addAll(insertElementList);
        elementList.addAll(updateElementList);
        elementList.addAll(deleteElementList);

        for (Element element : elementList) {
            /* id 参数值 返回值 sql */
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sqlText = element.getTextTrim();
            //封装mappedStatement
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            //设置SQLType
            if (element.getName().toUpperCase().equals(SQLType.SELECT.toString().toUpperCase())) {
                mappedStatement.setSqlType(SQLType.SELECT);
            } else if (element.getName().toUpperCase().equals(SQLType.INSERT.toString().toUpperCase())) {
                mappedStatement.setSqlType(SQLType.INSERT);
            }else if(element.getName().toUpperCase().equals(SQLType.UPDATE.toString().toUpperCase())){
                mappedStatement.setSqlType(SQLType.UPDATE);
            }else{
                mappedStatement.setSqlType(SQLType.DELETE);
            }
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }


    }
}
